package com.jh.fcsm.util.io;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

/**
 * File转MultipartFile 互转工具
 *
 * @author szx
 * @date 2022/04/28 16:17:58
 */
public class FileConvertUtils implements Serializable {
    private static final Logger logger = LoggerFactory.getLogger(FileConvertUtils.class);
    /**
     * File转MultipartFile
     *
     * @param file
     * @return
     */
    public static MultipartFile createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try(FileInputStream fis = new FileInputStream(file)){
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
        } catch (IOException e) {
            logger.error("创建MultipartFile失败");
        }
        MultipartFile multipartFile = new CommonsMultipartFile(item);
        return multipartFile;
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) {
        File toFile = null;
        if (file!=null && file.getSize() > 0) {
            try(InputStream ins  = file.getInputStream()){
                toFile = new File(file.getOriginalFilename());
                //获取流文件
                try ( OutputStream os = new FileOutputStream(toFile)){
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                        os.write(buffer, 0, bytesRead);
                    }
                } catch (Exception e) {
                    logger.error("MultipartFile 转 File失败");
                }
            } catch (Exception e) {
                logger.error("MultipartFile 转 File失败");
            }
        }
        return toFile;
    }
}

